//
//  CYProjectCateViewController.m
//  cyydt
//
//  Created by chu on 2019/1/17.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYProjectCateViewController.h"

#import "CYProjectCollectionViewCell.h"
#import "CYCategrayModel.h"
#import "CYProjectDetailViewController.h"

@interface CYProjectCateViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, DOPDropDownMenuDataSource,DOPDropDownMenuDelegate>
{
    NSArray *_moneyArr;
    NSArray *_paixuArr;
    
//    CYCategrayModel *_selBigCate;//选中的大分类
//    CYCategrayModel *_selSmallCate;//选中的小分类
//
//    NSString *_selFunds;//金额
//    NSString *_selSort;//排序方式
}
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) NSMutableDictionary *muParam;

@property (nonatomic, strong) DOPDropDownMenu *menu;

@property (nonatomic, strong) CYCategrayModel *selBigCate;

@property (nonatomic, strong) CYCategrayModel *selSmallCate;

@property (nonatomic, strong) NSString *selFunds;

@property (nonatomic, strong) NSString *selSort;

@end

@implementation CYProjectCateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"分类";
//    [self RightsetupNavgationItemWithpictureName:@"zxm_ss"];
    
    [self.view addSubview:self.collectionView];
    
    [self getDataWithParam:self.param];
    [self.muParam setDictionary:self.param];
    
    _moneyArr = @[@"全部", @"3万以下", @"3-8万", @"5-10万", @"10-20万", @"20万以上"];
    _paixuArr = @[@"智能排序", @"项目关注度", @"投资额度由低到高", @"投资额度由高到低"];
    // 添加下拉菜单
    DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:44];
    menu.delegate = self;
    menu.dataSource = self;
    menu.indicatorColor = RGBOF(0xF43636);
    menu.textSelectedColor = RGBOF(0xF43636);
    [self.view addSubview:menu];
    _menu = menu;
    //当下拉菜单收回时的回调，用于网络请求新的数据
    __weak typeof(self)weakself = self;
    _menu.finishedBlock=^(DOPIndexPath *indexPath){
        if (indexPath.item >= 0) {
            NSLog(@"收起:点击了 %ld - %ld - %ld 项目",(long)indexPath.column,(long)indexPath.row,(long)indexPath.item);
            if (indexPath.column == 0) {
                CYCategrayModel *model = weakself.cateArr[indexPath.row];
                weakself.selBigCate = model;
                NSArray *child = model.child;
                if (indexPath.item == 0) {
                    weakself.selSmallCate = nil;
                }else{
                    weakself.selSmallCate = child[indexPath.item];
                }
            }
            
        }else {
            if (indexPath.column == 1) {
                if (indexPath.row == 0) {
                    weakself.selFunds = @"0";
                }else if (indexPath.row == 1){
                    weakself.selFunds = @"10";
                }else if (indexPath.row == 2){
                    weakself.selFunds = @"15";
                }else if (indexPath.row == 3){
                    weakself.selFunds = @"5";
                }else if (indexPath.row == 4){
                    weakself.selFunds = @"6";
                }else if (indexPath.row == 5){
                    weakself.selFunds = @"11";
                }
            }else if (indexPath.column == 2){
                if (indexPath.row == 0) {
                    weakself.selSort = @"enbrand desc";
                }else if (indexPath.row == 1){
                    weakself.selSort = @"gbooks desc";
                }else if (indexPath.row == 2){
                    weakself.selSort = @"funds asc";
                }else if (indexPath.row == 3){
                    weakself.selSort = @"funds desc";
                }
            }else{
                weakself.selBigCate = weakself.cateArr[indexPath.row];
            }
            NSLog(@"收起:点击了 %ld - %ld 项目",(long)indexPath.column,(long)indexPath.row);
        }
        
        [weakself SelFinishInitParam];
    };

    if (!self.param[@"catid"]) {
        NSNumber *big_catid = self.param[@"big_catid"];
        NSInteger big = 0;
        for (int i = 0; i < self.cateArr.count; i++) {
            CYCategrayModel *bigModel = self.cateArr[i];
            if ([bigModel.catid integerValue] == [big_catid integerValue]) {
                _selBigCate = bigModel;
                big = i;
                [menu selectIndexPath:[DOPIndexPath indexPathWithCol:0 row:big]];
            }
        }
        self.title = _selBigCate.catname;
    }else{
        NSNumber *big_catid = self.param[@"big_catid"];
        NSNumber *catid = self.param[@"catid"];
        NSInteger bigNum = 0;
        NSInteger childNum = 0;
        for (int i = 0; i < self.cateArr.count; i++) {
            CYCategrayModel *bigModel = self.cateArr[i];
            if ([bigModel.catid integerValue] == [big_catid integerValue]) {
                bigNum = i;
                _selBigCate = bigModel;
                NSLog(@"bigModel.catname -- %@",bigModel.catname)
                NSArray *child = bigModel.child;
                for (int j = 0; j < child.count; j++) {
                    CYCategrayModel *childModel = child[j];
                    if ([childModel.catid integerValue] == [catid integerValue]) {
                        _selSmallCate = childModel;
                        NSLog(@"childModel.name -- %@",childModel.catname)
                        childNum = j;
                        [menu selectIndexPath:[DOPIndexPath indexPathWithCol:0 row:bigNum item:childNum]];
                        break;
                    }
                }
                self.title = _selSmallCate.catname;
            }
        }
    }

    //     创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
//        [menu selectDefalutIndexPath];
//    [menu selectIndexPath:[DOPIndexPath indexPathWithCol:0 row:0 item:0]];
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)SelFinishInitParam{
    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithCapacity:0];
    [muDic setObject:@"3" forKey:@"type"];
    [muDic setObject:@1 forKey:@"page"];

    if (_selBigCate) {
        self.title = _selBigCate.catname;
        if ([_selBigCate.catname isEqualToString:@"全部分类"]) {
            
        }else{
            [muDic setObject:_selBigCate.catid forKey:@"big_catid"];
            if (_selSmallCate) {
                [muDic setObject:_selSmallCate.catid forKey:@"catid"];
                self.title = _selSmallCate.catname;
            }
        }
        
    }
    if (_selFunds) {
        [muDic setObject:_selFunds forKey:@"funds"];
    }else{
        [muDic setObject:@"0" forKey:@"funds"];
    }
    
    if (_selSort) {
        [muDic setObject:_selSort forKey:@"sort"];
    }else{
        [muDic setObject:@"enbrand desc" forKey:@"sort"];
    }
    
    [self getDataWithParam:muDic];
    
    [self.muParam removeAllObjects];
    [self.muParam setDictionary:muDic];
}

- (void)setCateArr:(NSArray *)cateArr{
    NSMutableArray *muarr = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary *dic in cateArr) {
        NSMutableDictionary *bigDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        if (dic[@"child"]) {
            NSArray *child = dic[@"child"];
            NSMutableArray *childArr = [NSMutableArray arrayWithArray:child];
            [childArr insertObject:@{@"catname":@"全部"} atIndex:0];
            [bigDic setObject:childArr forKey:@"child"];
        }
        CYCategrayModel *model = [CYCategrayModel modelWithDictionary:bigDic];
        [muarr addObject:model];
    }
    CYCategrayModel *model = [[CYCategrayModel alloc] init];
    model.catname = @"全部分类";
    [muarr insertObject:model atIndex:0];
    _cateArr = muarr;
}

- (void)RighttouchEvent{
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
    detail.model = self.dataSourceArr[indexPath.row];
    [[AppDelegate sharedAppDelegate] pushViewController:detail];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.dataSourceArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CYProjectCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CYProjectCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[CYProjectCollectionViewCell alloc] init];
    }
    cell.model = self.dataSourceArr[indexPath.item];
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CYProjectModel *model = self.dataSourceArr[indexPath.item];
    UIView *view = [[Tool sharedInstance] setSignView:model.mode andBackgroundColor:RGBOF(0xF5F7FB) andTitleColor:RGBOF(0x97A2B9) Height:20 andFont:[UIFont systemFontOfSize:12] andMargin_x:8 andMargin_y:8 andMaxWidth:kWindowW - 150];
    return CGSizeMake(kWindowW, 115 + view.frame.size.height);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeZero;
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(0, 0, 10, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

#pragma DOPDropDownMenuDelegate
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return 3;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    if (column == 0) {
        return self.cateArr.count;
    }else if (column == 1){
        return _moneyArr.count;
    }else {
        return _paixuArr.count;
    }
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        CYCategrayModel *model = self.cateArr[indexPath.row];
        return model.catname;
    } else if (indexPath.column == 1){
        return _moneyArr[indexPath.row];
    } else {
        return _paixuArr[indexPath.row];
    }
}

// new datasource

- (NSString *)menu:(DOPDropDownMenu *)menu imageNameForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    return nil;
}

- (NSString *)menu:(DOPDropDownMenu *)menu imageNameForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    return nil;
}

// new datasource

- (NSString *)menu:(DOPDropDownMenu *)menu detailTextForRowAtIndexPath:(DOPIndexPath *)indexPath
{

    return nil;
}

- (NSString *)menu:(DOPDropDownMenu *)menu detailTextForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    return nil;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
    if (column == 0) {
        if (row == 0) {
            return 0;
        }
        CYCategrayModel *model = self.cateArr[row];
        return model.child.count;
    }
    return 0;
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        if (indexPath.row == 0) {
            return @"";
        }
        CYCategrayModel *model = self.cateArr[indexPath.row];
        NSArray *child = model.child;
        CYCategrayModel *childmodel = child[indexPath.item];

        return childmodel.catname;
    }
    return nil;
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        
    }else if (indexPath.column == 1){
        
    }else{
        
    }
    if (indexPath.item >= 0) {
        NSLog(@"点击了 %ld - %ld - %ld 项目",(long)indexPath.column,(long)indexPath.row,(long)indexPath.item);
    }else {
        NSLog(@"点击了 %ld - %ld 项目",(long)indexPath.column,(long)indexPath.row);
    }
}

- (void)getDataWithParam:(NSDictionary *)param{
    self.page = 1;
    NSLog(@"param --- %@",param);
    __weak typeof(self)weakself = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
//        NSLog(@"项目列表 ---- %@",responseResult);
        if ([weakself.collectionView.mj_header isRefreshing]) {
            [weakself.collectionView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                [weakself.dataSourceArr removeAllObjects];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    [weakself.dataSourceArr addObject:model];
                }
                [weakself.collectionView reloadData];
            }else{
                [weakself.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)getMoreDataWithParam:(NSDictionary *)param{
    self.page ++;
    __weak typeof(self)weakself = self;

    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:param];
    [muDic setObject:[NSNumber numberWithInteger:self.page] forKey:@"page"];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:muDic ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"项目列表 ---- %@",responseResult);
        if ([weakself.collectionView.mj_footer isRefreshing]) {
            [weakself.collectionView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [weakself.view makeToast:ResErrorMessage];
            weakself.page --;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    [weakself.dataSourceArr addObject:model];
                }
                [weakself.collectionView reloadData];
            }else{
                weakself.page --;
                [weakself.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wuneir"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"当前页面没有内容！";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:RGBOF(0x999999)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    // 空白页面被点击时开启动画，reloadEmptyDataSet
    
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //居左约束
        UICollectionViewFlowLayout *leftAlignedLayout = [[UICollectionViewFlowLayout alloc] init];
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, kWindowW, kWindowH - 44 - Height_NavBar) collectionViewLayout:leftAlignedLayout];
        _collectionView.backgroundColor = BackGroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

        [_collectionView registerNib:[UINib nibWithNibName:@"CYProjectCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CYProjectCollectionViewCell"];
        __weak typeof(self)weakself = self;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself SelFinishInitParam];
        }];
        
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakself getMoreDataWithParam:weakself.muParam];
        }];
        
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
    }
    return _collectionView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}

- (NSMutableDictionary *)muParam{
    if (!_muParam) {
        _muParam = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _muParam;
}

@end
